package com.example.demo.base;

import lombok.Data;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * ElasticsearchBasePo
 *
 * @author 陈学礼
 * @date 2020/6/3 11:51
 * 你是一段成熟的代码，要学会自己改bug
 */
@Data
public class ElasticsearchBasePo implements Serializable {

    private String id;

    private String index;

    private String type;

    private Map<String, Object> source;

    /**
     * 获取键值对map
     *
     * @return
     * @throws IllegalAccessException
     */
    public final Map<String, Object> toMap() throws IllegalAccessException {
        return toMap(this.getClass());
    }

    /**
     * 根据反射获取对象键值对
     *
     * @param clazz
     * @return
     * @throws IllegalAccessException
     */
    private Map<String, Object> toMap(Class<?> clazz) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        if (clazz != null) {
            // 获取字段
            Field[] fieldArray = clazz.getDeclaredFields();
            for (Field field : fieldArray) {
                field.setAccessible(true);
                String key = field.getName();
                Object value = field.get(this);
                map.put(key, value);
            }
            // 获取当前对象的父类
            Class<?> parentClass = clazz.getSuperclass();
            // 设置进值数据
            map.putAll(toMap(parentClass));
        }
        return map;
    }

}
